#! /usr/bin/env python
# -*- coding: utf-8 -*-

from distutils.cmd           import Command
from distutils.command.build import build
from distutils.command.clean import clean
from distutils.core          import setup
from distutils.spawn         import find_executable
from distutils.dist          import Distribution
from distutils               import log
import sys
import os
import subprocess

class myDistribution(Distribution):
    def __init__(self, attrs=None):
        self.pbddls = None
        Distribution.__init__(self, attrs)

class myBuild(build):

    """ This is "build" command depending on 'protoc' command.  """
    def run(self):
        self.run_command('protoc')
        return build.run(self)

class doProtoc(Command):

    description = '"protoc" command. This compiles ProtocolBuffer DDL to python program.'
    user_options = []

    def initialize_options(self):
        self.sources = None
        pass

    def finalize_options(self):
        self.ddls= self.distribution.pbddls
        pass

    def run(self):
        for ddl in self.ddls:
            compileProtoc(ddl)

protoc = find_executable("protoc")

def compileProtoc(source):

    if protoc == None:
        print >>sys.stderr, "Can't find protoc command."
        sys.exit(-1)

    output = "szlcln/" + os.path.basename(source.replace(".proto", "_pb2.py"))
    if not os.path.exists(source):
        print >>sys.stderr, "%s: no sush as file." % source
        sys.exit(-1)

    if (not os.path.exists(output) or
        (os.path.exists(source) and
        os.path.getmtime(source) > os.path.getmtime(output))):
        print "Generating %s..." % output

        d = os.path.dirname(source)
        protoc_command = [ protoc, "-I", d, "--python_out=szlcln", source ]
        if subprocess.call(protoc_command) != 0:
          sys.exit(-1)

def find(p):
    for (root, dirs, files) in os.walk(p):
        for f in files:
            yield os.path.join(root, f)

class myClean(clean):
    def run(self):
        clean.run(self)
        if self.all:
            for f in find("."):
                if f.endswith("_pb2.py"):
                    log.info("removing '%s'", f)
                    if not self.dry_run:
                        os.remove(f)

if __name__ == '__main__':
  setup(distclass = myDistribution,
        cmdclass = {'protoc': doProtoc, 'build': myBuild, 'clean': myClean},
        name = 'sctableapi',
        version = '0.9.0',
        packages = [ 'szlcln' ],
        license = 'Apache License, Version 2.0',
        description = 'SC table handling API',
        long_description = "Sawzall Clone Table handling API",
        pbddls = [ '../aggr/src/main/protobuf/table.proto' ]
        )
